package com.lu.system.filter;

import com.lu.common.utils.TokenUtils;
import com.lu.system.sysLog.domain.SysLog2DO;
import com.lu.system.sysLog.service.SysLog2Service;
import com.lu.system.user.domain.UserDO;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@WebFilter(filterName = "logFilter", urlPatterns = "/*")
public class LogFilter implements Filter {

    @Autowired
    private SysLog2Service sysLog2Service;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        String url = ((HttpServletRequest) servletRequest).getRequestURI();
        Map<String, String[]> map = ((HttpServletRequest) servletRequest).getParameterMap();
        String params = "";
        boolean flag = true;
        for(String key : map.keySet()){
            String[] ss = map.get(key);
            String val = "";
            for(String s : ss){
                val += s+"|";
            }
            val = val.substring(0,val.length()-1);
            if(key.equals("access_token")){
                if(val.equals("")){
                    flag = false;
                }
            }else {
                params += "key:"+key+",value:"+val+"&";
            }
            System.out.println(params);
        }
        if(!params.equals("")){
            params = params.substring(0,params.length()-1);
        }
        if(url.equals("/")){
            flag = false;
        }else if(url.equals("/index")){
            flag = false;
        }else if(url.equals("/system/management/user/save")){
            flag = false;
        }
        if(flag){
            UserDO userDO = null;
            try {
                userDO = TokenUtils.parseJwtForUserInfo((HttpServletRequest) servletRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SysLog2DO logDO = new SysLog2DO();
            logDO.setCreateTime(new Date());
            logDO.setUpdateTime(new Date());
            logDO.setUserId(userDO.getUserId());
            logDO.setUserName(userDO.getName());
            logDO.setUrl(url);
            logDO.setParams(params);
            logDO.setHost(servletRequest.getRemoteHost());
            logDO.setPort(servletRequest.getRemotePort()+"");
            sysLog2Service.save(logDO);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
